#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
require Exporter;
use strict;
use SIM_settings;
use CGI qw(param);

#my $httpUser = $ENV{'REMOTE_USER'} || die "Oops no env found for SREMOTE_USER.";
my $module = $ARGV[0];
my $tool = $ARGV[1];
my $action = $ARGV[2];
my $option1 = $ARGV[3];
my $option2 = $ARGV[4];
my $option3 = $ARGV[5];
my $option4 = $ARGV[6];


sub catFile {
  my $output = "";
  my ($file) = @_;
  open FH, $file or $output = "none";
# $output = readline FH;
  $output = <FH>;
  close FH;
  return $output;
}

sub catFileLine {
  my $outPut = "";
  my ($file) = @_;
  open FH, $file or $outPut = "$file";
  $outPut = <FH>;
  close FH;
  chomp($outPut);  # remove the newline
  return $outPut;
}

sub printFileLine {
  my $file = "@_[0]";
  my $varName = "@_[1]";
  my $rest = "@_[2]";
  my $logFile = "@_[3]";
  my $oldVal = catFileLine ("$file");
# print ("Update file=$file, varName=$varName, content:$rest<BR>");
  if ( "$oldVal" ne "$rest" ) {
    open(OUT, ">$file") || die "cannot create $file: $! (file=$file, varName=$varName, rest=$rest)";
    if ( "$logFile" ne "quiet" ) {
      print ("$varName is gewijzigd, oud:$oldVal nieuw:$rest<BR>");
    }
    print OUT $rest;
    close(OUT);
  }
}

sub testParam {
  my $file = "@_[0]";
  my $parameter = "@_[1]";
  my $update = "@_[2]";
  my $result = param("$parameter");
  if ( "$result" eq "" ) {
#   print("cat ");
    $result = &catFileLine("$file");
  } else {
    if ( "$update" eq "upd" ) { 
      printFileLine("$file","$parameter","$result","nquiet");
    }
  }
# print("$result $file<BR>");
  return("$result");
}

sub testNameStrict {
  my $testname = "@_[0]";
  my $type = "@_[1]";
  if ( "$type" eq "word" ) {
    $testname =~ tr#a-zA-Z[\xE0][\xE8][\xEC][\xF2][\xF9]##cd;
  } else {
    $testname =~ tr#a-zA-Z0-9[\@][\.][\-]#A#cds;
  }
  #print ("testname=$testname");
  return $testname;
}

sub testMkDir {
  my $dirName = "@_[0]";
  if ( !-d $dirName ) {
    system "mkdir -p $dirName";
  }
}

sub printHead {
  my $dispHead = "@_[0]";
  print("
        <TABLE WIDTH=100% BORDER=0 CELLSPACING=0><TR BGCOLOR=#EEEEEE><TD COLSPAN=3><CENTER>
        Options:
        <A HREF=$httpScriptName?$module+$tool+testEnv+perl>PerlEnv</A> <FONT COLOR=#333333>|</FONT>
        <A HREF=$httpScriptName?$module+$tool+testEnv+env>ShellEnv</A> <FONT COLOR=#333333>|</FONT>
        <A HREF=$httpScriptName?$module+$tool+testDeps>Test dependancies</A> <FONT COLOR=#333333>|</FONT>
        <A HREF=$httpScriptName?$module+$tool+testCmd>Command</A>
	</TD></TR>
	</TABLE>
        ");
}

sub testDeps {
  print("<CENTER><H2>Testing modules and dependancies</H2>");
  system(" $SIMparam{'SIMtestDeps'} 2>&1 ");
}

sub testCmd {
  print("<CENTER>");
  my $num = "@_[0]";
  my $testCmd = param('testCmd');
# print("testCmd: num=$num, testCmd=$testCmd, SIM_History=$SIM_History.<HR>");
  if (( "$num" ne "none" ) and ( "$num" ne "" )){
    open ( HIST, "$SIM_History");
    my @lines = <HIST>;
    close HIST;
    $testCmd = $lines[$num];
  }
  print("
    <FORM method=post Action=$httpScriptName?$module+$tool+testCmd>
      <INPUT NAME=testCmd Size=90 VALUE=\"$testCmd\" Type=text>
      <INPUT TYPE=submit Value=Run>
    </FORM></TD>
        ");
  if ( "$testCmd" ne "" ) {
    print("<HR>Running command \"$testCmd\".</CENTER><PRE>");
    system(" $testCmd 2>&1 ");
    system(" echo \"$testCmd\" >> $SIM_History ");
  } else {
    open ( HIST, "$SIM_History");
    my @lines = <HIST>;
    close HIST;
    print("<PRE>");
    my $num = 0;
    foreach my $regel (@lines) {
      $num++;
    }
    my $maxNum = 40;
    if ( $num gt $maxNum ) {
      my $firstNum = $num - $maxNum;
#     print("Removing $firstNum lines.");
      open ( HIST, ">$SIM_History");
      my $num = 0;
      foreach my $dispNum ($firstNum .. $maxNum) {
        print HIST ("$lines[$dispNum]");
        print("<A HREF=$httpScriptName?$module+$tool+testCmd+$num>$lines[$dispNum]</A>");
        $num++;
      }
      close HIST;
    } else {
      my $num = 0;
      foreach my $regel (@lines) {
        print("<A HREF=$httpScriptName?$module+$tool+testCmd+$num>$regel</A>");
	$num++;
      }
    }
  }

}

sub readUpdParam {
  my $workFile = "@_[0]";
  my $name = "@_[1]";
  my $type = "@_[2]";
  my $param = param("$name");
  if ( "$type" eq "fill" ) {
    $param=~s/ /_/g;
  }
  if ( "$param" eq "" ) {
    $param = catFileLine("$workFile");
  } else {
    printFileLine("$workFile","$name","$param");
  }
  return $param;
}

sub grepMain {
  my $searchString = "@_[0]";
  chdir $SIMparam{'SIMmainDir'};
  my @result = `grep -R $searchString *`;
  print("<CENTER><BR><B>Search results for $searchString</B><HR><TABLE>");
  foreach my $entry (@result) {
    my ( $file, $data ) = split(':', $entry, 2);
    $data =~ s/>/&gt;/g;
    $data =~ s/</&lt;/g;
    print("<TR><TD BGCOLOR=#DDFFFF>$file</TD><TD BGCOLOR=#FFDDFF>$data</TD></TR>");
  }
  print("</TABLE>");
}

sub testEnv {
  my $testType = "@_[0]";
  my %testHash = ();
  my $dispString;
  if ( "$testType" eq "perl" ) {
    %testHash = %SIMparam;
    $dispString = "Perl hash for \$SIMparam{\$key}";
  } else {
    %testHash = %ENV;
    $dispString = "Shell environment";
  }
  my ($k,$t);
  my %paramType = ();
  foreach $k (sort keys %testHash) {
    my $v = $testHash{$k};
    if ( -l $v ) {
      $paramType{$k} = "link";
    } elsif ( -d $v ) {
      $paramType{$k} = "dir";
    } elsif ( -x $v ) {
      $paramType{$k} = "bin";
    } elsif ( -f $v ) {
      $paramType{$k} = "file";
    } else {
      $paramType{$k} = "var";
    } 
  }
  print("<CENTER>
           <B>$dispString</B>.
         <TABLE>
	   <TR BGCOLOR=#88FFFF><TD COLSPAN=2>key</TD><TD COLSPAN=2>type</TD><TD>value</TD></TR>");
  foreach my $k (sort {$paramType{$a} cmp $paramType{$b} } keys %paramType) {
    if ( "$testHash{$k}" ne "" ) {
      print "<TR><TD><A HREF=$httpScriptName?$module+$tool+grep+$k>$k</A></TD>
                 <TD>=&gt;</TD><TD>$paramType{$k}</TD><TD>=&gt;</TD><TD>$testHash{$k}</TD></TR>";
    }
  }
  print("</TABLE>(All types are tested for file type.)");
}

#--------------------------- Main ---------------------------
printHead;



if ( "$action" eq "testCmd" ) {
  testCmd($option1);
} elsif ( "$action" eq "testEnv" ) {
  testEnv($option1);
} elsif ( "$action" eq "testDeps" ) {
  &testDeps;
} elsif ( "$action" eq "grep" ) {
  grepMain($option1);
} else {
  print("Oops, action $action not found.");
}
